package com.chromatic.competition.repository;

import android.content.Context;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.chromatic.competition.model.UserMessage;
import com.chromatic.competition.utils.TimestampUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.time.LocalDateTime;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import retrofit2.Response;

public class ChatRepository {
    private final Context context;
    private final OkHttpClient client;
    private WebSocket webSocket;

    public ChatRepository(Context context, OkHttpClient client) {
        this.context = context;
        this.client = client;
    }

    /**
     * 建立WebSocket连接
     *
     * @param senderId  发送者ID
     * @param friendId  好友ID
     */
    private void connect(int senderId, int friendId) {
        Request request = new Request.Builder()
                .url("ws://snake-konginchrist.com/instantMessaging")
                .build();

        webSocket = client.newWebSocket(request, new WebSocketListener() {
            public void onOpen(WebSocket webSocket, Response response) {
                webSocket.send("senderId: " + senderId);
                webSocket.send("FriendId: " + friendId);
                // 连接开启后的处理...
            }

            @Override
            public void onMessage(@NonNull WebSocket webSocket, @NonNull String text) {
                // 收到消息后的处理，例如更新messagesLiveData...
            }

            @Override
            public void onClosing(@NonNull WebSocket webSocket, int code, @NonNull String reason) {
                webSocket.close(1000, null);
            }

            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                // 连接失败后的处理...
            }
        });
    }

    /**
     * 断开WebSocket连接
     */
    public void disconnect() {
        // 当不再需要时，关闭WebSocket连接
        if (webSocket != null) {
            webSocket.close(1000, "App closed");
        }
    }

    /**
     * 获取与好友的聊天消息
     *
     * @param friendId 好友ID
     * @return 包含聊天消息列表的LiveData对象
     */
    public LiveData<List<UserMessage>> getMessages(int friendId) {
        MutableLiveData<List<UserMessage>> messagesLiveData = new MutableLiveData<>();
//        chatService.getMessages(friendId).enqueue(new Callback<List<Message>>() {
//            @Override
//            public void onResponse(@NonNull Call<List<Message>> call, @NonNull Response<List<Message>> response) {
//                if (response.isSuccessful()) {
//                    messagesLiveData.setValue(response.body());
//                }
//            }
//
//            @Override
//            public void onFailure(@NonNull Call<List<Message>> call, Throwable t) {
//                // Handle error
//            }
//        });
        return messagesLiveData;
    }

    /**
     * 发送聊天消息给好友
     *
     * @param friendId       好友ID
     * @param messageContent 消息内容
     */
    public void sendMessage(int friendId, String messageContent) {
        SharedPreferences prefs = context.getSharedPreferences("login_info", Context.MODE_PRIVATE);
        String user = prefs.getString("user", "");
        int senderId = 0;
        try {
            JSONObject jsonObject = new JSONObject(user);
            // 如果 "user_id" 字段的值是浮点数，可以使用以下代码将其转换为整数
            senderId = (int) (jsonObject.getDouble("user_id"));
            // 使用提取到的 "user_id" 进行其他操作...
        } catch (JSONException e) {
            e.printStackTrace();
        }
        UserMessage userMessage = new UserMessage(TimestampUtil.getCurrentMicrosecondTimestamp(),
                senderId, friendId, messageContent, LocalDateTime.now());

        // 将消息发送到后端服务
//        chatService.sendMessage(message).enqueue(new Callback<Void>() {
//            @Override
//            public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
//                // Handle response
//            }
//
//            @Override
//            public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
//                // Handle error
//            }
//        });

        // 同时将消息发送到 WebSocket
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("friendId", friendId);
            jsonObject.put("message", messageContent);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // 通过WebSocket连接发送JSON消息
        webSocket.send(jsonObject.toString());
    }
}